package com.lvmama.controller.rhino.visitors;

import com.alibaba.fastjson.JSONArray;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.DateUtil;
import com.lvmama.pojo.entity.rhino.visitors.VisitorInfo;
import com.lvmama.service.rhino.topic.StatisticCodeService;
import com.lvmama.service.rhino.visitor.VisitorService;
import com.lvmama.utils.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/visitors")
@Slf4j
public class VisitorsController {

    @Autowired
    private VisitorService visitorService;

    @Autowired
    private StatisticCodeService statisticCodeService;


    /**
     * @Title: visitorChartData
     * @Description: 访客图表数据
     * @param @param chooseTime
     * @param @return 设定文件
     * @return Map<String,Object> 返回类型
     * @throws
     */
    @PostMapping("/visitorChartData")
    @ResponseBody
    public Result<Map<String, Object>> visitorChartData(@RequestParam(value = "chooseTime")String chooseTime, @RequestParam(value = "type")String type) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        VisitorInfo visitor = new VisitorInfo();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");

        visitor.setStartDate(beginDate);
        visitor.setEndDate(endDate);
        List<VisitorInfo> visitorListByDate = new ArrayList<VisitorInfo>();
        List<VisitorInfo> visitorListByPlatform = new ArrayList<VisitorInfo>();
        try {
            if ("new_visitor".equals(type)) {
                visitorListByDate = visitorService.getVisitorListByDate(visitor);
                visitorListByPlatform = visitorService.getVisitorListByPlatform(visitor);
            } else {
                visitorListByDate = visitorService.getRegisterListByDate(visitor);
                visitorListByPlatform = visitorService.getRegisterListByPlatform(visitor);
            }
        } catch (Exception e) {
            log.error("visitorChartData error{}",e);
        }
        int amount = 0;
        // 柱状图数据
        JSONArray arr = new JSONArray();
        List<String> platformList = new ArrayList<>();
        for (VisitorInfo platform : visitorListByPlatform) {
            platformList.add(platform.getPlatformCode());
            amount += platform.getAmount();
            JSONObject o = new JSONObject();
            o.put("platform",platform.getPlatformCode());
            o.put("amount",platform.getAmount());
            arr.add(o);
        }
        // 折线图数据
        String[] dateAxis = DateUtil.getBetweenTime(beginDate, endDate, "yyyy/MM/dd");
        List<String> dateList = Arrays.asList(dateAxis);

        JSONArray arr2 = new JSONArray();
        for(String date:dateList){
            for (String platform : platformList) {
                Integer amountTomal = 0;
                for (VisitorInfo visitorinfo : visitorListByDate) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    String time = sdf.format(visitorinfo.getOperDate());
                    if (platform.equals(visitorinfo.getPlatformCode()) && date.equals(time)) {
                        amountTomal += visitorinfo.getAmount();
                    }
                }
                JSONObject o = new JSONObject();
                o.put("platform",platform);
                o.put("time",date);
                o.put("amount",amountTomal);
                arr2.add(o);
            }
        }
        resultMap.put("platformList", platformList);
        resultMap.put("amount", amount);
        resultMap.put("jsonData", arr);
        resultMap.put("jsonData2", arr2);
        return Result.success(resultMap);
    }


    /**
     * @Title: visitorPlatformData
     * @Description: 平台各渠道详细数据
     * @param @param chooseTime
     * @param @param type
     * @param @param platform
     * @param @return 设定文件
     * @return Map<String,Object> 返回类型
     * @throws
     */
    @PostMapping("/visitorPlatformData")
    @ResponseBody
    public Result<Map<String, Object>> visitorPlatformData(@RequestParam("chooseTime")String chooseTime, @RequestParam("type")String type, @RequestParam("platform")String platform) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        VisitorInfo visitor = new VisitorInfo();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        visitor.setStartDate(beginDate);
        visitor.setEndDate(endDate);
        List<VisitorInfo> visitorListByPlatform = new ArrayList<VisitorInfo>();
        try {
            if ("new_visitor".equals(type)) {
                if ("wap".equals(platform)) {
                    platform = "2g53";
                }else if("pc".equals(platform)) {
                    platform = "2qw6";
                }
                visitor.setPlatformCode(platform);
                visitorListByPlatform = visitorService.getVisitorListByChannel(visitor);
            } else {
                List<String> statisticCodeList = getPlatformCodeList(platform);
                visitor.setStatisticCodeList(statisticCodeList);
                visitorListByPlatform = visitorService.getRegisterListByChannel(visitor);
            }
        } catch (Exception e) {
            log.error("visitorPlatformData error{}",e);
        }
        // pc,wap有两级渠道 app只有一级下载渠道
        Map<String, Integer> firstChennelMap = new HashMap<String, Integer>();
        // pc,wap
        String[] firstChannelArr = { "直接", "SEO", "SEM", "分享" };
        int[] firstAmountArr = new int[4];
        Map<String, Integer> SEOChennelMap = new HashMap<String, Integer>();
        Map<String, Integer> SEMChennelMap = new HashMap<String, Integer>();
        Map<String, Integer> shareChennelMap = new HashMap<String, Integer>();

        for (VisitorInfo visitorInfo : visitorListByPlatform) {
            int amount = visitorInfo.getAmount();
            String channelCode = visitorInfo.getChannelCode().replaceAll("\"","");
            if ("pc".equals(platform) || "2g53".equals(platform) || "wap".equals(platform) || "2qw6".equals(platform)) {
                String channelName = statisticCodeService.getNameByCode(channelCode).getName();
                if (channelCode.equals("116yq5")) {
                    firstAmountArr[0] += amount;
                } else if (channelCode.startsWith("123")) {
                    firstAmountArr[1] += amount;
                    SEOChennelMap.put(channelName, amount);
                } else if (channelCode.startsWith("12h")) {
                    firstAmountArr[2] += amount;
                    SEMChennelMap.put(channelName, amount);
                } else if (channelCode.startsWith("121")) {
                    firstAmountArr[3] += amount;
                    shareChennelMap.put(channelName, amount);
                }

            } else {
                firstChennelMap.put(channelCode, amount);
            }
        }
        // 获取前十条数据

        firstChennelMap = ToolUtils.sortByValueDesc(firstChennelMap);
        int i = 0;
        int amount = 0;
        JSONArray arr = new JSONArray();
        for (Map.Entry<String, Integer> entry : firstChennelMap.entrySet()) {
            if (i < 10) {
                JSONObject o = new JSONObject();
                o.put("name",entry.getKey());
                o.put("value",entry.getValue());
                arr.add(o);
            } else {
                amount += entry.getValue();
            }
            i++;
        }
        if (firstChennelMap.size() > 10) {
            JSONObject o = new JSONObject();
            o.put("name","其他");
            o.put("value",amount);
            arr.add(o);
        }
        resultMap.put("jsonArr", arr);
        resultMap.put("firstChannelArr", firstChannelArr);
        resultMap.put("firstAmountArr", firstAmountArr);
        resultMap.put("SEOChennelMap", JSONObject.fromObject(SEOChennelMap).toString());
        resultMap.put("SEMChennelMap", JSONObject.fromObject(SEMChennelMap).toString());
        resultMap.put("shareChennelMap", JSONObject.fromObject(shareChennelMap).toString());
        return Result.success(resultMap);
    }

    /**
     * @Title: getChanenlData
     * @Description: 获取最小粒度的渠道数据
     * @param @param map
     * @param @return 设定文件
     * @return Map<String,Object> 返回类型
     * @throws
     */
    @PostMapping("/visitorChannelData")
    @ResponseBody
    public Result<Map<String, Object>> getChanenlData(@RequestParam("channelJson")String channelJson) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        JSONArray jsonArr = new JSONArray();
        int num = 0;
        if (StringUtils.isNotEmpty(channelJson)) {
            JSONObject jsonObject = JSONObject.fromObject(channelJson);
            for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = jsonObject.getString(key);
                num += Integer.parseInt(value);
                JSONObject o = new JSONObject();
                o.put("name",key);
                o.put("value",Integer.parseInt(value));
                jsonArr.add(o);
            }
        }
        resultMap.put("num", num);
        resultMap.put("jsonArr", jsonArr);
        return Result.success(resultMap);
    }


    /**
     * @Title: getPlatformCodeList
     * @Description: 获取平台相关code
     * @param @param platform_code
     * @param @return 设定文件
     * @return List<String> 返回类型
     * @throws
     */
    private List<String> getPlatformCodeList(String platform_code) {
        List<String> statisticCodeList = new ArrayList<>();
        try {
            statisticCodeList = statisticCodeService.getDeviceCodeByLikeName(platform_code);
        } catch (Exception e) {
            log.error("getPlatformCodeList error:{}",e);
        }
        return statisticCodeList;
    }







}
